package com.lxx.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxx.wiki.domain.entity.Ebook;
import com.lxx.wiki.domain.entity.EbookExample;
import com.lxx.wiki.domain.req.EbookPageQueryReq;
import com.lxx.wiki.domain.req.EbookQueryReq;
import com.lxx.wiki.domain.req.EbookSaveReq;
import com.lxx.wiki.domain.resp.EbookQueryResp;
import com.lxx.wiki.domain.resp.PageResp;
import com.lxx.wiki.mapper.EbookMapper;
import com.lxx.wiki.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class EbookService {

    @Autowired
    private EbookMapper ebookMapper;


    public PageResp<EbookQueryResp> list(EbookPageQueryReq ebookPageQueryReq) {
        // 对于所有带条件的，基本写法都是这两行，创建一个规则
        EbookExample example = new EbookExample();
        EbookExample.Criteria criteria = example.createCriteria();

        if (!ObjectUtils.isEmpty(ebookPageQueryReq.getName())) {
            criteria.andNameLike("%" + ebookPageQueryReq.getName() + "%");
        }

        // 使用PageHeler的注意事项：
        // 页码是从1开始，不是0
        // startPage调用建议紧挨着你要查询列表的语句前面
        PageHelper.startPage(ebookPageQueryReq.getPage(), ebookPageQueryReq.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(example);
        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);

        List<EbookQueryResp> ebookQueryRespList = BeanCopyUtils.copyBeanList(ebookList, EbookQueryResp.class);

        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setRows(ebookQueryRespList);

        return pageResp;
    }

    public void save(EbookSaveReq ebookSaveReq) {
        Ebook ebook = BeanCopyUtils.copyBean(ebookSaveReq, Ebook.class);
        if (ObjectUtils.isEmpty(ebook.getId())) {
            // 新增
            // id数据库设置了自增
            ebookMapper.insert(ebook);
        } else {
            // 修改
            ebookMapper.updateByPrimaryKey(ebook);
        }

    }

    public void del(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }

    public List<EbookQueryResp> all(EbookQueryReq ebookQueryReq) {
        EbookExample example = new EbookExample();
        EbookExample.Criteria criteria = example.createCriteria();
        if (!ObjectUtils.isEmpty(ebookQueryReq.getCategory2Id()) && ebookQueryReq.getCategory2Id() > 0) {
            criteria.andCategory2IdEqualTo(ebookQueryReq.getCategory2Id());
        }

        List<Ebook> ebookList = ebookMapper.selectByExample(example);
        List<EbookQueryResp> ebookQueryRespList = BeanCopyUtils.copyBeanList(ebookList, EbookQueryResp.class);
        return ebookQueryRespList;
    }
}
